package cn.edu.sicnu.cardgame.ui

import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import cn.edu.sicnu.cardgame.Card
import cn.edu.sicnu.cardgame.CardMatchingGame
import cn.edu.sicnu.cardgame.R
import cn.edu.sicnu.cardgame.data.ProfileRepository

class GameActivity : AppCompatActivity() {

    private lateinit var grid: GridLayout
    private lateinit var tvScore: TextView
    private lateinit var btnRestart: Button
    private lateinit var btnExit: Button

    private var game: CardMatchingGame? = null
    private val buttons: MutableList<Button> = mutableListOf()
    private val cardCount: Int = 16

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game)

        tvScore = findViewById(R.id.tvScore)
        grid = findViewById(R.id.gridCards)
        btnRestart = findViewById(R.id.btnRestart)
        btnExit = findViewById(R.id.btnExit)

        btnRestart.setOnClickListener { startNewGame() }
        btnExit.setOnClickListener { finish() }
        setupGrid()
        startNewGame()
    }

    private fun setupGrid() {
        grid.removeAllViews()
        buttons.clear()
        for (i in 0 until cardCount) {
            val btn = Button(this)
            btn.isAllCaps = false
            btn.textSize = 22f
            btn.text = "?"
            btn.tag = i
            val params = ViewGroup.MarginLayoutParams(
                0,
                0
            )
            params.setMargins(8, 8, 8, 8)
            btn.layoutParams = params
            btn.setBackgroundResource(R.drawable.card_back)
            btn.setOnClickListener {
                val index = it.tag as Int
                onCardTapped(index)
            }
            buttons.add(btn)
            grid.addView(btn)
        }
        grid.post { resizeCards() }
    }

    private fun startNewGame() {
        game = CardMatchingGame(cardCount)
        for (i in 0 until cardCount) {
            val card = game!!.cardAtIndex(i)
            buttons[i].isEnabled = true
            buttons[i].text = getFaceFor(card)
            buttons[i].alpha = 1.0f
            updateButton(i)
        }
        updateScore()
    }

    private fun onCardTapped(index: Int) {
        val g = game ?: return
        g.chooseCardAtIndex(index)
        // Update all buttons to reflect states
        for (i in 0 until cardCount) updateButton(i)
        updateScore()
        // update high score
        ProfileRepository.tryUpdateHighScore(g.score)
    }

    private fun updateButton(index: Int) {
        val card = game!!.cardAtIndex(index)
        val btn = buttons[index]
        val isFaceUp = card.isChosen || card.isMatched
        btn.text = if (isFaceUp) getFaceFor(card) else "?"
        // red for hearts/diamonds
        val red = card.suit == "♥" || card.suit == "♦"
        btn.setTextColor(if (isFaceUp && red) 0xFFD32F2F.toInt() else 0xFF000000.toInt())
        btn.setBackgroundResource(if (isFaceUp) R.drawable.card_face else R.drawable.card_back)
        btn.isEnabled = !card.isMatched
        btn.alpha = if (card.isMatched) 0.4f else 1.0f
    }

    private fun updateScore() {
        tvScore.text = getString(R.string.label_score) + "： " + (game?.score ?: 0)
    }

    private fun getFaceFor(card: Card): String {
        return card.toString()
    }

    private fun resizeCards() {
        // Make each card with standard 3:4 ratio (width:height = 3:4)
        val columns = grid.columnCount
        val totalWidth = grid.width - grid.paddingLeft - grid.paddingRight
        val cellWidth = (totalWidth / columns) - 16 // Account for margins
        val cellHeight = (cellWidth * 4 / 3).toInt() // 3:4 ratio
        for (i in 0 until grid.childCount) {
            val v = grid.getChildAt(i)
            val lp = v.layoutParams as ViewGroup.MarginLayoutParams
            lp.width = cellWidth
            lp.height = cellHeight
            v.layoutParams = lp
        }
    }
}

